<template>
	<view>
		<!-- 导航条 -->
		<view class="cu-custom" :style="{height: $wanlshop.wanlsys().height + 'px' }">
			<view class="cu-bar fixed bg-bgcolor" :style="{
				height: $wanlshop.wanlsys().height + 'px', 
				paddingTop: $wanlshop.wanlsys().top + 'px'
			}">
				<view class="action">
					<text class="wlIcon-fanhui1" style="margin-left: 0;" @tap="$wanlshop.back(1)"></text>
				</view>
				<view class="content" :style="{top: $wanlshop.wanlsys().top + 'px'}">
					{{isEdit ? '修改商品' : '发布商品'}}
				</view>
			</view>
		</view>
		
		<view class="edgeInsetTop"></view>
		<form @submit="formSubmit">
			<view class="cu-list menu solid-bottom">
				<view class="cu-item" style="min-height:150rpx;"  @tap="handleMainImage()">
					<view class="content">
						<text style="font-size: 30rpx;">商品主图：</text>
					</view>
					<view class="action">
						<image v-if="image" :src="isEdit ? $wanlshop.oss(image, 100, 100) : image" mode="aspectFill" class="radius-bock" style="width: 120rpx;height:120rpx;"></image>
						<view v-else class="text-gray flex flex-direction bg-gray justify-center align-center radius-bock" style="width: 120rpx;height:120rpx;">
							<text class="wlIcon-tianjia"></text>
							<view class="margin-top-xs text-sm">添加主图</view>
						</view>
					</view>
				</view>
			</view>
			
			<view class="cu-form-group">
				<view class="title">商品标题：</view>
				<input placeholder="请输入商品标题" name="title" v-model="title"></input>
			</view>
			
<!-- 			<view class="cu-form-group">
				<view class="title">月销量(基数)：</view>
				<input placeholder="月销量(基数)" name="sales" v-model="sales"></input>
			</view>
						 -->												
			<view class="cu-form-group" >
				<view class="title">商品相册：</view>
			</view>			
			<view class="wanlfind-add-container__main bg-white">
				<view class="grid col-4 grid-square flex-sub padding-lr-bj">
					<view v-if="images.length > 0" v-for="(item, index) in images" :key="index">
						<view class="item" @tap="handlePreview(index)">
							<image :src="$wanlshop.oss(item, 100, 100)" mode="widthFix"></image>
						</view>
						<view class="tag" @tap="handleDelImage(index)">
							<text class="wlIcon-31guanbi text-white"></text>
						</view>
					</view>			
					<view v-if="images.length < 8" @tap="handleImage()">
						<view class="item">
							<view class="text-lg text-gray">
								<text class="wlIcon-tianjia"></text>
								<view v-if="images.length === 0" class="margin-top-xs text-sm">添加图片</view>
								<view v-else class="margin-top-xs text-sm">继续添加</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 商品详情 -->
			<view class="cu-form-group" >
				<view class="title">商品详情：</view>
			</view>
			<view style="color:orangered;font-size:24rpx; padding:10rpx 20rpx;">一行为一项说明, 左边为说明项，最多18个字符(非空),右边为说明项备注(备注可为空),可点击 + 号,增加行</view>
			<view class="listwrapper">
				<view class="descitem" v-for="(item,index) in inputList" :key="index">
					<input class="descinput" placeholder="非空" maxlength="18" style="flex:1" v-model="item.text" />
					<input class="" placeholder="可空" style="flex-basis:100rpx;border-radius:10rpx;border:1rpx solid #aaa;height:60rpx;magin-left:10rpx;" v-model = "item.number"/>
					<input class="" placeholder="可空" style="flex-basis:100rpx;border-radius:10rpx;border:1rpx solid #aaa;height:60rpx;magin-left:10rpx;" v-model = "item.price"/>
					<text @click="addline(index)">{{index == 0? "+" : "-"}}</text>
				</view>
			</view>
			
			
			
			<view class="cu-form-group" >
				<view class="title">商品详情相册：</view>
			</view>			
			<view class="wanlfind-add-container__main bg-white">
				<view class="grid col-4 grid-square flex-sub padding-lr-bj">
					<view v-if="descImages.length > 0" v-for="(item, index) in descImages" :key="index">
						<view class="item" @tap="handlePreview1(index)">
							<image :src="$wanlshop.oss(item, 100, 100)" mode="widthFix"></image>
						</view>
						<view class="tag" @tap="handleDelImage1(index)">
							<text class="wlIcon-31guanbi text-white"></text>
						</view>
					</view>			
					<view v-if="descImages.length < 8" @tap="handleImage1()">
						<view class="item">
							<view class="text-lg text-gray">
								<text class="wlIcon-tianjia"></text>
								<view v-if="descImages.length === 0" class="margin-top-xs text-sm">添加图片</view>
								<view v-else class="margin-top-xs text-sm">继续添加</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			

			
		<!-- 	<view class="bg-white">
				<view class="padding-bj bg-gray margin-lr-bj radius-bock">
					<editor
						id="editor"
						@ready="onEditorReady"
						@input="onEditorInput"
						placeholder="请输入商品详情~"
					/>
				</view>
			</view> -->
			
			<view class="cu-form-group" >
				<view class="title">商品价格：</view>
				<input placeholder="请输入商品价格" name="realPrice" v-model="realPrice" @input="handlePriceInput"></input>
				<view class="title">是否打折</view>
				<switch @change="changeCostStatus" v-model="isCost" :class="isCost?'checked':''" :checked="isCost?true:false"/>
			</view>
			
			
			<view class="cu-form-group"  v-show="isCost">
				<view class="title">折扣价：<!-- <span style="margin-left: 20px;">{{ price }} 元</span> --></view>
				<input type="text"  pattern="[0-9]*\.?[0-9]*" placeholder="请输入商品折扣价" name="price" v-model="price" @input="handleCostPriceInput"></input>
			</view>
			
			
			<!--<view class="cu-form-group" v-show="isCost">
				<view class="title">商品折扣：{{cost}}</view>-->
				<!-- <input placeholder="请输入商品折扣"  name="cost" v-model="cost" @input="handleCostInput"></input> -->
			<!-- </view> -->

			<view class="cu-form-group">
				<view class="title">库存数量：</view>
				<input placeholder="请输入库存数量" name="stock" v-model="stock" @input="handleStockInput"></input>
			</view>
			<view class="cu-form-group" >
				<view class="title">上架状态：</view>
				<picker @change="statusChange" :value="statusIndex" :range="statusArr">
					<view class="uni-input" style="color: grey;">{{ statusArr[statusIndex]}}</view>
				</picker>
				<text class="wlIcon-fanhui2"></text>
			</view>
			
			<!-- <view class="cu-form-group" >
				<view class="title">销售渠道：</view>
				<picker @change="channelChange" :value="channelIndex" :range="channelArr">
					<view class="uni-input flex justify-between" style="color: grey;">
						{{channelArr[channelIndex]}}
						<text class="wlIcon-fanhui2"></text>
					</view>
				</picker>
			</view> -->
			
			
			<!--底部-->
			<view class="safeAreaBottom"></view>
			<view class="wanlfind-add-container__foot">
				<view class="cu-bar tabbar foot flex flex-direction bg-white align-center">
					<view class="padding-lr-bj" style="width: 100%;">
						<button form-type="submit" class="wanl-bg-redorange">{{isEdit ? '修改商品' : '发布商品'}}</button>
					</view>					
				</view>
			</view>
		</form>

			
	</view>
</template>

<script>
	import graceChecker, { isNumber } from '@/common/graceChecker';
	import { mapState } from 'vuex';
	export default {
		computed: {
			...mapState(['user'])
		},
		data() {
			return {
				sales:50,
				title:'', //商品标题
				status:'normal', //上架状态nomal是上架    hidden是下架
				statusIndex: 0,
				statusArr: ['上架', '下架'],
				channel:2, //销售渠道 1线上  2线下
				channelIndex:0,
				channelArr:['线上', '线下'], 
				image:'', //商品主图
				images:[], //商品详情图
				descImages:[],
				content: '',
				price:'',
				stock: 0,
				realPrice:'',
				cost: 0,
				isEdit:false,
				productId:'',
				isCost: false,
				inputList:[{text:"",price:"",number:""}],
			}
		},
		onLoad(e) {
			//获取编辑页信息
			if(e.detail !== undefined){
				this.isEdit = true
				let item = JSON.parse(e.detail)

				this.image = item.image
				this.images = item.images
				this.title = item.title
				this.content = item.content
				this.price = item.price
				this.status = item.status
				this.isCost = item.is_cost
				this.cost = item.cost
				this.realPrice = item.real_price
				//this.channel = item.channel
				this.productId = item.id
				this.stock = item.stock
				this.statusIndex = this.status === 'normal' ? 0 : 1;
				//this.channelIndex = this.channel === 1 ? 0 : 1;
				console.log(item);
				if(item.descimages){
					this.descImages = item.descimages.split(",");
				}
				
				
				
				if(this.content){
					let carr = this.content.split("#*#");
					this.inputList = [];
					carr.forEach(item =>{
						let itemArr = item.split("***")
						this.inputList.push({
							text:itemArr[0],
							number:itemArr[1] !== undefined?itemArr[1]:"",
							price:itemArr[2] !== undefined?itemArr[2]:""
						});
					})
				}
			
			}
		},
		methods: {	
			
			addline(index){
				if(index == 0){
					this.inputList.push({text:"",price:"",number:""})
				}else{
					this.inputList.splice(index,1);
				}
				
			},
			
			
			hasNoMoreThanTwoDecimalPlaces(number) {
			    // 确保输入是一个数字
			    if (typeof number !== 'number' || isNaN(number)) {
			        return false;
			    }
			
			    // 将数字转换为字符串
			    const numberStr = number.toString();
			
			    // 查找小数点的位置
			    const decimalIndex = numberStr.indexOf('.');
			
			    // 如果没有小数点，则小数位数为0，满足条件
			    if (decimalIndex === -1) {
			        return true;
			    }
			
			    // 获取小数点后的部分
			    const decimalPart = numberStr.slice(decimalIndex + 1);
			
			    // 检查小数点后的字符数量是否不超过两位
			    return decimalPart.length <= 2;
			},
			
			
			handleCostPriceInput(){
				if(!this.hasNoMoreThanTwoDecimalPlaces(this.price*1)){
					this.$nextTick(()=>{
						this.price = Math.round((this.price*1 + Number.EPSILON) * 100) / 100;
					})
					
					uni.showToast({
						title:'不能超过两位小数',
						icon:"none"
					})
					return;
				}
				if(!this.realPrice){
					uni.showToast({
						title:'请先设置商品原价',
						icon:"none"
					})
					this.$nextTick(()=>{
						this.price = "";
					})
					return;
				}
				
				//计算折扣
				this.$nextTick(()=>{
					this.cost = ((this.price*1/this.realPrice*1)*10).toFixed(3)
				})
				
			},
			
			
			//上架状态
			statusChange: function(e) {
				this.statusIndex = e.detail.value
				this.status = this.statusIndex === 1 ? 'hidden' : 'normal'
			},
			changeCostStatus(e) {
				this.isCost = e.target.value;
				if(!e.target.value){
					this.cost = 0;
					this.price = this.realPrice
				}
				if(e.target.value){
					if(this.cost != 0){
						this.price = (this.realPrice * this.cost / 10).toFixed(2)
					} else {
						this.price = this.realPrice
					}
				}
			},
			handleCostInput(e) {
			// 	this.$nextTick(() => {
			// 		let inputValue = e.detail.value;
			// 		  // 正则表达式：匹配最多两位小数的数字
			// 		if(inputValue > 10){
			// 			this.cost = 9.9;
			// 		} else if(inputValue < 0){
			// 			this.cost = 0;
			// 		} else if(inputValue.includes('.')) {
			// 		   const parts = inputValue.split('.');
			// 		   if (parts[1].length > 1) {
			// 			 // 保留两位小数
			// 			 this.cost = parts[0]+ '.' + parts[1].slice(0, 1);
			// 		   }
			// 		}
			// 		if(this.cost != 0){
			// 			this.price = (this.realPrice * this.cost / 10).toFixed(2)
			// 		} else {
			// 			this.price = this.realPrice
			// 		}
			// 	})
			
			},
			handlePriceInput(e) {
				
				this.$nextTick(()=>{
					if(!this.hasNoMoreThanTwoDecimalPlaces(this.realPrice*1)){
						uni.showToast({
							title:"不能超过两位小数",
							icon:"none"
						})
						this.realPrice = "";
						return ;
					}
				})
				
				
				// this.$nextTick(() => {
				// 	if(this.cost != 0){
				// 		this.price = (this.realPrice * this.cost / 10).toFixed(2)
				// 	} else {
				// 		this.price = this.realPrice
				// 	}
				// })
			},
			handleStockInput(e) {
				this.$nextTick(() => {
					let inputValue = e.detail.value;
					if(inputValue && (inputValue < 0 || !isNumber(inputValue))){
						this.stock = 0;
					}
				})
			},
			//销售渠道
			channelChange: function(e) {
				console.log(e)
				this.channelIndex = e.detail.value
				this.channel = this.channelIndex +1
			},
			//表单提交
			formSubmit: function(e) {
				//定义表单规则			
				let rule = [
					{name: 'title', checkType: 'string', checkRule: '3,32', errorMsg: '商品名称，至少3-32字符'},
				];	
					
				if(this.inputList.length > 0){
					let inputlist = this.inputList.filter(item=>item.text)
					if(inputlist.length > 0){
						let inputmap = inputlist.map(item=>{return item.text+"***"+item.number+"***"+item.price});
						this.content = inputmap.join("#*#")
					}
				}	
				//进行表单检查
				let formData = e.detail.value;
				formData.image = this.image
				formData.images = this.images
				formData.content = this.content
				formData.channel = 2
				formData.status = this.status
				formData.isCost = this.isCost
				formData.cost = this.cost
				formData.price = this.price
				formData.realPrice = this.realPrice
				formData.descimages = this.descImages
			
				if(formData.image === ''){
					this.$wanlshop.msg('请上传商品主图~');
					return
				}
				if(formData.content === ''){
					this.$wanlshop.msg('请输入商品详情~');
					return
				}
				let priceRule = /^-?\d+(\.\d+)?$/.test(formData.realPrice)
				if(!priceRule){
					this.$wanlshop.msg('请输入商品价格~');
					return
				}
				// if(this.isCost){
				// 	let costRule = /^-?\d+(\.\d+)?$/.test(formData.cost)
				// 	if(!costRule){
				// 		this.$wanlshop.msg('请输入折扣率~');
				// 		return
				// 	}
				// }
				
				let checkRes = graceChecker.check(formData, rule);
				if (checkRes) {
					console.log(formData)
				
					// return
					if(this.isEdit){
						formData.id = this.productId
						uni.request({
							url: '/wanlshop/product/updateProduct/', 
							method: 'POST',
							data: formData,
							success: res => {
								// 提示
								setTimeout(()=>{
									uni.redirectTo({
										url:'/pages/business/product'
									})
								},500);
								this.$wanlshop.msg('修改成功');
							}
						});
					} else{
						uni.request({
							url: '/wanlshop/product/addProduct', 
							method: 'POST',
							data: formData,
							success: res => {
								// 提示
								setTimeout(()=>{
									uni.redirectTo({
										url:'/pages/business/product'
									})
								},500);
								this.$wanlshop.msg('添加成功');
							}
						});
					}
					
				} else {
					this.$wanlshop.msg(graceChecker.error);
				}
			},
			
			//1张主图
			handleMainImage() {
				uni.chooseImage({
					count: 1, // 默认1
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: (res) => {
						if (res.tempFilePaths) {
							res.tempFilePaths.map((item, index) => {
								// 延迟触发一下
								uni.request({
									url: '/wanlshop/common/uploadData',
									success: updata => {
										uni.getImageInfo({
											src: res.tempFilePaths[0],
											success: image => {
												uni.uploadFile({
													url: updata.data.uploadurl,
													filePath: image.path,
													name: 'file',
													formData:updata.data.storage == 'local' ? null : updata.data.multipart,
													success: data => {
														let src = 'https://adminshop.12sxb.cn/' + JSON.parse(data.data).data.url
														this.image = src								
													},
													fail: error =>{
														uni.showToast({title: JSON.parse(error.data).msg, icon: 'error', position: true});
													}
												});
											}
										});
										
										
									}
								});
							})
						}
					}
				});
			},
			
			//8张详情图
			handleImage() {
				uni.chooseImage({
					crop: {
						quality: 60
					},
					count: 8, // 默认8
					success: res => {
						uni.request({
							url: '/wanlshop/common/uploadData',
							success: updata => {
								for (let i = 0; i < res.tempFilePaths.length; i++) {
									// 读取图片宽高
									uni.getImageInfo({
										src: res.tempFilePaths[i],
										success: image => {
											uni.uploadFile({
												url: updata.data.uploadurl,
												filePath: image.path,
												name: 'file',
												formData:updata.data.storage == 'local' ? null : updata.data.multipart,
												success: data => {
													this.images.push(JSON.parse(data.data).data.url);
												},
												fail: error =>{
													uni.showToast({title: JSON.parse(error.data).msg, icon: 'error', position: true});
												}
											});
										}
									});
								}
							}
						});
					}
				});
			},
			handlePreview(index) {
				let imgArr = [];
				for (let item of this.images) {
					imgArr = imgArr.concat(this.$wanlshop.oss(item, 500));
				}
				uni.previewImage({
					urls: imgArr,
					current: imgArr[index],
					indicator: 'number'
				});
			},
			handleDelImage(index) {
				this.images.splice(index, 1);
			},
			
			
			
			
			handleImage1() {
				uni.chooseImage({
					crop: {
						quality: 60
					},
					count: 8, // 默认8
					success: res => {
						uni.request({
							url: '/wanlshop/common/uploadData',
							success: updata => {
								for (let i = 0; i < res.tempFilePaths.length; i++) {
									// 读取图片宽高
									uni.getImageInfo({
										src: res.tempFilePaths[i],
										success: image => {
											uni.uploadFile({
												url: updata.data.uploadurl,
												filePath: image.path,
												name: 'file',
												formData:updata.data.storage == 'local' ? null : updata.data.multipart,
												success: data => {
													this.descImages.push(JSON.parse(data.data).data.url);
												},
												fail: error =>{
													uni.showToast({title: JSON.parse(error.data).msg, icon: 'error', position: true});
												}
											});
										}
									});
								}
							}
						});
					}
				});
			},
			handlePreview1(index) {
				let imgArr = [];
				for (let item of this.descImages) {
					imgArr = imgArr.concat(this.$wanlshop.oss(item, 500));
				}
				uni.previewImage({
					urls: imgArr,
					current: imgArr[index],
					indicator: 'number'
				});
			},
			handleDelImage1(index) {
				this.descImages.splice(index, 1);
			},
			
			
			
			
			
			
			
			
			onEditorInput(e) {
				this.content = e.detail.html;
			},
			
			onEditorReady() {
				// #ifdef MP-BAIDU
				this.editorCtx = requireDynamicLib('editorLib').createEditorContext('editorId');
				// #endif
			
				// #ifdef APP-PLUS || H5 ||MP-WEIXIN
				//console.log(this.content)
				if(this.content){  //编辑
					uni.createSelectorQuery().select('#editor').context((res)=>{   
						this.editorCtx = res.context
						this.editorCtx.setContents({
							html:this.content   
						})
						
					}).exec();
				} else{           //新增
					uni.createSelectorQuery()
						.select('#editor')
						.context(res => {
							this.editorCtx = res.context;  
						})
						.exec();
				}
										
				// #endif
			},
			
		}
	}
</script>

<style lang="scss" scoped>
	.cu-form-group uni-picker::after{
		display: none;
	}
	::v-deep .ql-container{
		min-height: 100rpx;
		height: 150rpx;
	}
	::v-deep .cu-form-group uni-picker{
		padding-right: 0;
	}
	.image-center {
		display: flex;
		justify-content: center
	}
	.upload{
		padding: 20rpx;
	}
	.upload-box{
		height: 240rpx;
		max-height: 300rpx;
	}
	.upload-item{
		display: flex;
		flex-direction: column;
		align-content: center;
		align-items: center;
		justify-items: center;
		justify-content: center;
		height: 100%;
		border: 1rpx solid #dddddd;
	}
	
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
	.grid {
		position: relative;
		.tag {
			position: absolute;
			top: 0rpx;
			right: 0rpx;
			z-index: 3;
			width: 40rpx;
			height: 40rpx;
			border-radius: 5500rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			text-align: center;
			overflow: hidden;
			background-color: #e6162c;
		}
	}
	
	.wanlfind-add-container__main .grid .item {
	    position: absolute;
	    top: 0;
	    bottom: 0;
	    left: 0;
	    right: 0;
	    z-index: 1;
	    display: flex;
	    justify-content: center;
	    align-items: center;
	    text-align: center;
	    border-radius: 9px;
	    overflow: hidden;
	    background-color: #f0f0f0;
	}
	
	.listwrapper{
		width:100%;
		padding:20rpx 40rpx;
		box-sizing: border-box;
		.descitem{
			width:100%;
			display:flex;
			justify-content: space-between;
			align-items: center;
			margin-top:10rpx;
			.descinput{
				flex:1;
				border:1rpx solid #aaa;
				height:60rpx;
				border-radius: 10rpx;
				padding:0 10rpx;
			}
			text{
				display:inline-block;
				font-size:60rpx;
				font-weight: bold;
				height:60rpx;
				line-height: 60rpx;
				margin-left:10rpx;
				width:60rpx;
				text-align: center;
			}
		}
	}
	
</style>
